package com.beerq.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.net.http.SslError;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.IOException;
import java.util.HashMap;

/**
 * 作者：minj on 2017/9/29 16:43
 * webview管理类
 */
public class WebViewUtil {

    static HashMap<String,String> mapFiles=new HashMap<String, String>();

    static {
        //字体库
        mapFiles.put("pfzj.ttf","fonts/pfzj.ttf");

        //css
        mapFiles.put("ionic.min.css","css/ionic.min.css");

        //js
        mapFiles.put("jquery.min.js","js/jquery.min.js");
        mapFiles.put("city.js","js/city.js");
        mapFiles.put("ad.js","js/ad.js");
        mapFiles.put("picker.min.js","js/picker.min.js");
        mapFiles.put("swiper.min.js","js/swiper.min.js");

        mapFiles.put("angular-cookies.min.js","js/angular-cookies.min.js");
        mapFiles.put("ionic.bundle.min.js","js/ionic.bundle.min.js");
        mapFiles.put("ionic.min.js","js/ionic.min.js");
        mapFiles.put("ionic-angular.min.js","js/ionic-angular.min.js");


        mapFiles.put("angular.min.js","js/angular.min.js");
        mapFiles.put("angular-animate.min.js","js/angular-animate.min.js");
        mapFiles.put("angular-resource.min.js","js/angular-resource.min.js");
        mapFiles.put("angular-sanitize.min.js","js/angular-sanitize.min.js");
        mapFiles.put("swiper.min.js","js/swiper.min.js");
        mapFiles.put("swiper.min.js","js/swiper.min.js");

    }


    public static void initWebView(final Context context, final WebView webView) {

        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
                    webView.goBack();
                    return true;
                }
                return false;
            }
        });


        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportZoom(false);
//
        if(!AppConfig.isNetworkAvailable(context)){
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }else {
            if(com.beerq.BuildConfig.DEBUG){
                webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            }else {
                webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
            }

        }



        webSettings.setAppCacheEnabled(true);

        webView.setWebViewClient(new WebViewClient() { //禁止超链接
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                WebResourceResponse response = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    response = getLocalResource(context, url);
                    if (response != null) {
                        return response;
                    }
                }
                return super.shouldInterceptRequest(view, url);
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                WebResourceResponse response = null;
                String url = request.getUrl().toString();
                response = getLocalResource(context, url);
                if (response != null) {
                    return response;
                }
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                webView.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);
//                context.showToast(R.string.no_network);
//                webView.setVisibility(View.GONE);

            }
        });

        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
//        webView.setInitialScale(60);
    }

    private static WebResourceResponse getLocalResource(Context context, String url) {

        WebResourceResponse response = null;

        String localFiles=matchLocalFiles(url);

        if (localFiles!=null) {
            try {
                response = new WebResourceResponse(getMimiType(localFiles), "UTF-8", context.getAssets().open(localFiles));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return response;

    }

    /***
     * 通过文件名获得文件的mime类型
     * @param url
     * @return
     */
    private static String getMimiType(String url){
        if (url.endsWith(".png")) {
            return "image/png";
        } else if (url.endsWith(".gif")) {
            return "image/gif";
        } else if (url.endsWith(".jpg")) {
            return "image/gif";
        } else if (url.endsWith(".jepg")) {
            return "image/jepg";
        } else if (url.endsWith(".js") ) {
            return "text/javascript";
        } else if (url.endsWith(".css") ) {
            return "text/css";
        } else if (url.endsWith(".html")) {
            return "text/html";
        }

        return "";

    }

    private static String matchLocalFiles(String url){

        for(String str:mapFiles.keySet() ){
            if(url.contains(str)){
                return mapFiles.get(str);

            }
        }
        return null;

    }


}
